#!/usr/bin/env python
#coding:utf-8

import tornado
from ..baseHandler import BaseHandler
from bson import ObjectId
from ..error import ErrorHandler

class PointsHandler(BaseHandler):

    #用户积分系统处理
    @tornado.gen.coroutine
    def get(self,userId):
        if not userId:
            return ErrorHandler.write_error(self,status_code=101,message="缺少用户ID信息")
        try:
            objectId = ObjectId(userId)
        except Exception as e:
            return  ErrorHandler.write_error(self,status_code=102,message=str(e))
        #用户积分信息返回,首先返回用户积分总数
        user_points = {}

        user_points = yield self.db.user_points.find_one({"user":userId})
        if not user_points:
            return self.response_msg(200,"积分获取成功",[{"user":userId,"total":0,"points_history":[]}])
        #若用户积分信息不空则继续查询积分获取记录
        user_points['points_history'] = {}
        user_points['points_history'] = yield self.db.points.find({"user":userId}).to_list(10)
        if not user_points['points_history']:
            return self.response_msg(200,"积分获取成功",[{"user":userId,"total":user_points['total'],"points_history":[]}])
        else:
            history = self.find_formart(user_points['points_history'])
            return self.response_msg(200,"积分获取成功",[{"user":userId,"total":user_points['total'],"points_history":history}])




handlers = [(r"/points/(.*)",PointsHandler),
            ]